package com.baizhi.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baizhi.utils.JWTUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * @Author：请允悲
 * @Slogan：拦截器
 * @Package：com.baizhi.interceptor
 * @Project：springbootjwt
 * @name：JWTInterceptor
 * @Date：2023/9/21 11:07
 * @Filename：JWTInterceptor
 */
public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HashMap<String, String> map = new HashMap<>();

        //获取请求头中的令牌
         String token = request.getHeader("token");
        try {
            //验证token
            JWTUtils.verify(token);
            map.put("msg","验证成功");
            map.put("state","true");
            return true;//放行请求

        }catch (SignatureVerificationException e){
            map.put("msg","//签名不一致异常");
            e.printStackTrace();
        }catch (TokenExpiredException e){
            map.put("msg","//令牌过期异常");
            e.printStackTrace();
        }catch (AlgorithmMismatchException e){
            map.put("msg","//算法不匹配异常");
            e.printStackTrace();
        }catch (Exception e){
            map.put("msg","无效token");
            e.printStackTrace();
        }
        map.put("state","false");//设置状态
        //将map转化为json jackson
         String json = new ObjectMapper().writeValueAsString(map);
         response.setContentType("application/json;charset=UTF-8");
         response.getWriter().println(json);
        return false;
    }
}
